package _5thread;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description:
 * @Author wangzhen
 * @Date 2022-06-08 21:40
 **/
public class ReentrantLockTest {

    static int size=10;
    static ReentrantLock reentrantLock=new ReentrantLock(true);

    public static void main(String[] args){


        //两个消费者线程消费10个包子
        //消费者1号
        Thread thread1=new Thread("1号"){

            @Override
            public void run() {

                while (true){

                    consume();
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    if(size<=0){
                        break;
                    }

                }

            }
        };

        //消费者2
        Thread thread2=new Thread("2号"){

            @Override
            public void run() {

                while (true){

                    consume();

                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    if(size<=0){
                        break;
                    }

                }

            }
        };

        thread1.start();
        thread2.start();
    }


    public static void consume(){

        try {
            reentrantLock.lock();

            size-=1;
            System.out.println(Thread.currentThread().getName()+"消费了1个包子,当前剩余"+size+"个包子");
        }finally {
            reentrantLock.unlock();
        }

    }
}
